//
//  AddressCell.m
//  QoilPublic
//
//  Created by SunChao on 2018/1/27.
//  Copyright © 2018年 孙超. All rights reserved.
//

#import "AddressCell.h"
@interface AddressCell()<UITextFieldDelegate>


@property (weak, nonatomic) IBOutlet UITextField *nameText;


@property (weak, nonatomic) IBOutlet UITextField *phoneText;

@end
@implementation AddressCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    [_nameText addTarget:self action:@selector(textFieldAction:) forControlEvents:UIControlEventEditingChanged];
    _nameText.tag = 1;
    _nameText.delegate = self;
    _nameText.clearButtonMode = UITextFieldViewModeAlways;
    [_phoneText addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _phoneText.tag = 2;
    _phoneText.delegate = self;
    _phoneText.keyboardType = UIKeyboardTypeNumberPad;
    _phoneText.clearButtonMode = UITextFieldViewModeAlways;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldAction:(UITextField *)texField{
    
    
    if (texField.text.length > 15) {
        
        texField.text = [texField.text substringToIndex:11];
        
    }
    if(texField.tag == 1){
        if(_nameBlock){
            _nameBlock(texField.text);
        }
    }
}
// 需要使用的textfield遵循代理

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.phoneText) {
        
         return [self validateNumber:string];
    }
    
    return YES;
}

- (BOOL)validateNumber:(NSString*)number {
   
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)textFieldDidChange:(UITextField *)textField

{
    
    if (textField == self.phoneText) {
        
        if (textField.text.length > 11) {
            
            textField.text = [textField.text substringToIndex:11];
            
        }
        
    }
    if(_phoneBlock){
        
        _phoneBlock(textField.text);
    }
}
@end
